package com.sbwebsocket.core.redis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sbwebsocket.core.config.WsAppConfig;
import com.sbwebsocket.core.model.bo.DirectMessageBody;
import com.sbwebsocket.core.model.bo.UnusualMessage;
import com.sbwebsocket.core.redis.model.contants.WsMessageRedisKeyPrefix;
import com.sbwebsocket.core.service.UnusualMessageManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @Auther: GSJ
 * @Date: 2022/2/16
 * @Description:
 * @version: 1.0
 */
@Slf4j
public class RedisDelayProcUnusualMessage implements UnusualMessageManager {

    @Autowired
    RedisModeUtil redisModeUtil;

    @Autowired
    RedisDirectMessageQueue redisDirectMessageQueue;

    @Autowired
    ObjectMapper objectMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    WsAppConfig appConfig;

    @Override
    public boolean save(String jsonMsg) {
        Boolean add = redisTemplate.opsForZSet().add(WsMessageRedisKeyPrefix.UNUSUAL_MSG_LIST, jsonMsg,
                appConfig.getUnusualMessageLingerMaxTime() + System.currentTimeMillis());
        return null == add ? false:add;
    }

    @Override
    public boolean reput(UnusualMessage msg) {
        /**
         * 重新把消息放回消费队列
         * step1: 检已经下线用户是否重新上线
         * step2: 若已经上线则把消息重新扔回对应的消费队列
         * step3: 否则抛弃消息
         */
        redisDirectMessageQueue.delivery(new DirectMessageBody(msg.getClientKey(), msg.getJsonBody()));
        return true;
    }

    @Override
    public boolean reput(String jsonMsg) {
        try {
            UnusualMessage directMessageBody = objectMapper.readValue(jsonMsg, UnusualMessage.class);
            if(log.isDebugEnabled()){
                log.debug("重新给异常离线客户端发送消息:{}",directMessageBody);
            }
            return reput(directMessageBody);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean save(UnusualMessage unusualMessage) {
        try {
            return this.save(objectMapper.writeValueAsString(unusualMessage));
        } catch (JsonProcessingException e) {
            log.error("redis保存异常消息失败!",e);
            return false;
        }
    }
}
